// scope related method
package repo

import (
	model "micro-oauth/datamodels"
	"micro-oauth/datamodels/params"
)

func (s *ServiceImpl) GetScopeById(scopeId uint64) *model.Scope {
	var scope model.Scope
	err := s.db.Where("id = ? ", scopeId).First(&scope).Error
	if err != nil {
		return nil
	}
	return &scope
}

func (s *ServiceImpl) AddScope(scope *model.Scope) error {
	return s.db.Create(scope).Error
}

func (s *ServiceImpl) ListScope(req *params.ScopeListRequest) (scopes []*model.Scope, total uint64, err error) {
	db := DefaultListDB(s.db, &req.ListRequest)
	if req.Name != "" {
		db = db.Where("name = ?", req.Name)
	}
	if req.Code != "" {
		db = db.Where("code = ?", req.Name)
	}
	db.Model(&model.Scope{}).Count(&total)
	if req.Limit != 0 {
		db = db.Limit(req.Limit)
	}
	if req.Offset != 0 {
		db = db.Limit(req.Offset)
	}
	err = db.Find(&scopes).Error
	if err != nil || len(scopes) == 0 {
		emptyResult := make([]*model.Scope, 0)
		return emptyResult, 0, err
	}
	return scopes, total, nil
}

func (s *ServiceImpl) UpdateScope(scope *model.Scope) error {
	return s.db.Save(scope).Error
}

func (s *ServiceImpl) DeleteScope(scopeId uint64) error {
	return s.db.Unscoped().Where(
		"id = ?", scopeId,
	).Delete(model.Scope{}).Error
}
